<html>
  <head>
    <title>Plan</title>
    <meta name="layout" content="main" />
    
    <script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>

    <script type="text/javascript">
    var map;
    var airportMarkers = [];
    var line;
    
    $(document).ready(function() 
	{
	    setLocations();
	});   

	if (typeof String.prototype.startsWith != 'function') 
	{ 
	  String.prototype.startsWith = function (str){ 
	    return this.indexOf(str) == 0; 
	  }; 
	} 

	function setMap(locSuccess, Lat, Lng)
	{
		if (locSuccess)
		{
			$('#latitude').val(Lat);
			$('#longitude').val(Lng);
		}
		else
		{
		    Lat = 43.913035;
		    Lng = -69.953589;
			$('#latitude').val(Lat);
			$('#longitude').val(Lng);
		}
        
        var myOptions = {
          zoom: 4,
          center: new google.maps.LatLng(Lat, Lng),
          mapTypeId: google.maps.MapTypeId.ROADMAP
         };

        map = null;
        map = new google.maps.Map(document.getElementById('map'), myOptions);
	}
	
	function setLocations()
	{		  
	  if (navigator.geolocation) 
	  {
	    navigator.geolocation.getCurrentPosition( 
			function (position)
			{  
				//$('#latitude').val(position.coords.latitude);
				//$('#longitude').val(position.coords.longitude);
				$('#UserLocation').html("Location: Latitude@"+position.coords.latitude + " Longitude@" + position.coords.longitude);
				setMap(true, position.coords.latitude, position.coords.longitude);
			}, 
	        // next function is the error callback
	        function (error)
	        {
	          switch(error.code) 
	          {
	            case error.TIMEOUT:
	            		$('#UserLocation').html("Error:Geolocation: Timeout");
	                    break;
	            case error.POSITION_UNAVAILABLE:
	            		$('#UserLocation').html("Error:Geolocation: Position unavailable");
	                    break;
	            case error.PERMISSION_DENIED:
	            		$('#UserLocation').html("Error:Geolocation: Permission denied");
	                    break;
	            case error.UNKNOWN_ERROR:
	            		$('#UserLocation').html("Error:Geolocation: Unknown error");
	                    break;
	          }
	          setMap(false, 0, 0);
	    	}
	  	);
	  }
	  else
	  {
	    //no browser support for HTML5 geolocation
	    setMap(false, 0, 0);
	    $('#UserLocation').html("Error:Geolocation: No Geolocation Support!");
	  }

	  var check = $('#UserLocation').html();
	  
	  if (check.startsWith("Error:"))
	  {
		  return false;
	  }
	  else
	  {
		  return true;
	  }  
	}

    function init() {
		alert("onload");
	}

    function addAirport(response, position) 
    {      
      //var airport = eval('(' + response.responseText + ')');
      var label = response.iata + " -- " + response.name;
      var marker = new google.maps.Marker({
          position: new google.maps.LatLng(response.lat, response.lng),
          title:label,
          map: map
      });
      
      if(airportMarkers[position] != null)
      {
        airportMarkers[position].setMap(null);
      }
      
      if(response.name != "Not found")
      {
        airportMarkers[position] = marker;
        marker.setMap(map);
      }
      
      document.getElementById("airport_" + position).innerHTML = response.name;
      drawLine();
      showHotelsLink();
    }
    
    function drawLine()
    {
      if(line != null)
      {
    	  line.setMap(null);
      }
      
      if(airportMarkers.length == 2)
      {
		var fpCoord = [
			airportMarkers[0].position,
			airportMarkers[1].position
		  ];

		line = new google.maps.Polyline({
			path: fpCoord,
			strokeColor: "#FF0000",
			strokeOpacity: 1.0,
			strokeWeight: 2
		});

		line.setMap(map);
      }
    }    

    function showHotelsLink()
    {
    	  if(airportMarkers[1] != null)
          {
    	    var hotels_link = document.getElementById("hotels_link");
    	    hotels_link.innerHTML = "<a href='#' onClick='loadHotels()'>Show Nearby Hotels...</a>";
    	  }
    }

    function loadHotels()
    {
      var url = "${createLink(controller:'hotel', action:'near')}";
      var params = "lat=" + airportMarkers[1].position.lat();
      params += "&lng=" + airportMarkers[1].position.lng();
      var xRequest = $.ajax(url,
      {
    	  dataType: "json",
    	  url: url,  
    	  data: params
      });

      xRequest.success(function(req){
           showHotels(req); 
      });

      xRequest.fail(function(req){
          displayError(req);
      });
    }

    function displayError(response)
    {
   	  var html = "response.status=" + response.status + "<br />";
   	  html += "response.responseText=" + response.responseText + "<br />";
   	  var hotels = document.getElementById("hotels");
   	  hotels.innerHTML = html;
    }

    function showHotels(response)
    {
   	  //var results = eval( '(' + response.responseText + ')');
   	  //var resultCount = 1 * results.ResultSet.totalResultsReturned;
   	  var resultCount = 1 * response.ResultSet.totalResultsReturned;
   	  var html = "<ul>";
   	  for(var i=0; i < resultCount; i++)
      {
   	    html += "<li>" + response.ResultSet.Result[i].Title + "<br />";
   	    html += "Distance: " + response.ResultSet.Result[i].Distance + "<br />";
   	    html += "<hr />";
   	    html += "</li>";
   	  }
   	  html += "</ul>";
   	  var hotels = document.getElementById("hotels");
   	  hotels.innerHTML = html;
   	}

    </script>
  </head>
  <body onload="init();" onunload="GUnload();">
  	<h1>Grails and Google Maps.</h1>
    <div class="body" style="width:100%; height:100%;">
		<div id="search" style="width:25%; float:left">
			<h2>Where to?</h2>
			<g:formRemote name="from_form"
			              url="[controller:'airportMapping', action:'iata']"
			              onSuccess="addAirport(data, 0)">
			  <table width="150px">
			  	<tr>
			  	  <td width="40px">From:</td>
			  	  <td width="40px"><input type="text" name="id" size="3"/></td>
			  	  <td><input type="submit" value="Search" /></td>
			  	</tr>
			  </table>
			</g:formRemote>
			<div id="airport_0"></div>
			<br/>
			<g:formRemote name="to_form"
			              url="[controller:'airportMapping', action:'iata']"
			              onSuccess="addAirport(data, 1)">
			  <table width="150px">
			    <tr>
			      <td width="40px">To:</td>
			      <td width="40px"><input type="text" name="id" size="3"/></td>
			      <td><input type="submit" value="Search" /></td>
			    </tr>
			  </table>
			</g:formRemote>
			<div id="airport_1"></div>
			<hr/>
			<div id="hotels_link"></div>
			<div style="height:400px;overflow:auto;">
				<div id="hotels"></div>
			</div>
	    </div>
		<div id="map" style="width:75%; height:95%; float:right"></div>
    </div>
    
    <hr width="95%"/>
	<div id="UserLocation"></div>

    <input id="latitude" type="hidden" name="Lat" value="">
    <input id="longitude" type="hidden" name="Lon" value="">
		
  </body>
</html>
